<?php

namespace Mobile\Controller;

/**
 * 房态接口
 * @modify trainyao 2016-01-23 创建
 */
class OrderController extends ParentController {

    protected function _initialize() {
        parent::_initialize();
        $this->validateUtil = new \Org\Util\Validate();
        $param = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'hotel' => 'notnull,notempty,id',
        );
        $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);

        $hotelId = $param['hotel'];
        $userId = $param['userId'];

        //检查操作权限
        $adminAuthorityLogic = A('Common/AdminAuthority', 'Logic'); 
        if (!in_array(ACTION_NAME, array('payHistory', 'getInfoByIdentity', 'getTransCurrencyRate'))) {
            $adminAuthorityLogic->check($hotelId, $userId);
        }
        //检查客栈是否已过期
        $hotelLogic = A('Common/Hotel', 'Logic');
        $hotelLogic->checkHotelActive($hotelId);
        $hotelLogic->checkHotelStatus($hotelId);
    }

    /**
     * 获取子订单数据
     * @modify trainyao 2016-01-23    创建
     * @version v1.0.0 ios
     */
    public function items() {
        $param = I('post.');

        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'hotel' => 'notnull,notempty,id',
            'start' => 'notempty,isDate',
            'token' => 'notnull,notempty',
        );
        $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);

        $userId = $param['userId'];
        $token = $param['token'];
        $this->checkMobileToken($userId, $token);

        $hotelId = $param['hotel'];
        if (!isset($param['start'])) {
            $start = date('Y-m-d', strtotime('-3 days'));
        } else {
            $start = $param['start'];
        }
        $end = date('Y-m-d', strtotime($start . ' +30 days'));

        $version = getCurrentVersion();
        // 获取子订单数据
        $orderLogic = A('Common/Order', 'Logic');
        try {
            $orderInfo = $orderLogic->getSubOrder($hotelId, null, 'within', $start, $end, null, null, null, null, null, null, true, null, null, $version);
            $orderInfo = $orderLogic->filteFrontActiveOrder($orderInfo['subOrder'], $start, $end);
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }
        $hourVersion = C('MOBILE_VERSION')['hour_room'];
        $longVersion = C('MOBILE_VERSION')['long_room'];
        // 处理子订单数据
        foreach ($orderInfo as $index => &$subOrder) {
            // 删除已删除房间的订单
            if ($subOrder['roomInfoDelete'] == IS_DELETE) {
                unset($orderInfo[$index]);
                continue;
            }
            if ($version < $hourVersion && $subOrder['hour'] > 0) {
                returnJson(403,999);
//                unset($orderInfo[$index]);
//                continue;
            }
            if ($version < $longVersion && $subOrder['month'] > 0) {
                unset($orderInfo[$index]);
                //returnJson(403,999);
            }
            if($subOrder['hour'] > 0 && $subOrder['status'] == ORDER_CANCELED) {
                unset($orderInfo[$index]);
                continue;
            }
            $subOrder['starttime'] = $subOrder['startdate'];
            $subOrder['endtime'] = $subOrder['enddate'];
            $subOrder['checkouttime'] = $subOrder['checkoutdate'];
            unset($subOrder['createtime']);
            unset($subOrder['creator']);
            $subOrder['suborder'] = $subOrder['id'];
            unset($subOrder['id']);
            $subOrder['roomId'] = $subOrder['roominfo_id'];
            unset($subOrder['roominfo_id']);
            $subOrder['roomType'] = $subOrder['roomtype_name'];
            unset($subOrder['roomtype_name']);
            $subOrder['roomName'] = $subOrder['roominfo_name'];
            unset($subOrder['roominfo_name']);
            $subOrder['night'] = $subOrder['realnight'];
            unset($subOrder['realnight']);
            $subOrder['channelName'] = $subOrder['order']['channelName'];
            $subOrder['name'] = $subOrder['order']['name'];
            $subOrder['areaCode'] = $subOrder['areacode'];
            unset($subOrder['areacode']);
            $subOrder['mobile'] = $subOrder['order']['mobile'];
            $subOrder['identity'] = $subOrder['order']['identity'];
            $subOrder['pay'] = $subOrder['payment'];
            unset($subOrder['payment']);
            $subOrder['price'] = $subOrder['order']['payment'];
            $subOrder['receipt'] = $subOrder['order']['receipt'];
            $subOrder['deposit'] = $subOrder['order']['deposit'];
            $subOrder['remark'] = $subOrder['order']['remark'];
            $subOrder['order'] = $subOrder['orderinfo_id'];
            unset($subOrder['orderinfo_id']);
            $subOrder['statusName'] = $orderLogic->statusMap[LANG_SET][$subOrder['status']];
            $subOrder['start'] = date('Y-m-d', strtotime($subOrder['startdate']));
            unset($subOrder['startdate']);
            $subOrder['end'] = date('Y-m-d', strtotime($subOrder['checkoutdate']));
            unset($subOrder['checkoutdate']);
            $subOrder['endDate'] = date('Y-m-d', strtotime($subOrder['enddate']));
            unset($subOrder['enddate']);
        }
        unset($subOrder);

        returnJson(200, 200, array(
            'today' => date('Y-m-d'),
            'startDate' => $start,
            'endDate' => $end,
            'orders' => array_values($orderInfo),
        ));
    }

    /**
     * 获取订单详细信息
     * @modify trainyao 2016-01-23    创建
     * @for v1.0.0 ios
     */
    public function detail() {
        $params = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'hotel' => 'notnull,notempty,id',
            'order' => 'notnull,notempty,id',
        );
        $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);
        $userId = $params['userId'];
        $token = $params['token'];
        $hotelId = $params['hotel'];
        
        //检验token
        $this->checkMobileToken($userId, $token);
        $orderInfoId = $params['order'];
        $orderLogic = A('Common/Order', 'Logic');
        $version = getVersion(array('2.0.18','2.0.17','2.0.13','2.0.11','2.0.08','2.0.01','2.0.00'));
        try {
            $orderInfo = $orderLogic->getOrderInfo($hotelId, $orderInfoId, true, true, $version);
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }
        //数据格式转换
        $data = array();

        $data['order'] = $orderInfo[0]['id'];
        $data['channelId'] = $orderInfo[0]['hotelchannel_id'];
        $data['channelName'] = $orderInfo[0]['channelName'];
        $data['receipt'] = $orderInfo[0]['receipt'];
        $data['deposit'] = $orderInfo[0]['deposit'];
        $data['orig'] = $orderInfo[0]['orig'];
        $data['discount'] = $orderInfo[0]['discount'];
        $data['discountrule'] = $orderInfo[0]['discountrule'];
        // 订单金额加上 其他消费待收金额
        $pay = $orderInfo[0]['payment'] + $orderInfo[0]['otherUncollectePrice'];
        $data['pay'] = number_format($pay, 2, '.','');
        //$data['pay'] = $orderInfo[0]['payment'];
        // 优惠券信息
        $data['couponType'] = $orderInfo[0]['couponType'];
        $data['couponRule'] = $orderInfo[0]['couponRule'];
        $data['remark'] = $orderInfo[0]['remark'];
        $data['name'] = $orderInfo[0]['name'];
        $data['mobile'] = $orderInfo[0]['mobile'];
        $data['identity'] = $orderInfo[0]['identity'];
        if ($version >= '2.0.11') {
            $data['areaCode'] = $orderInfo[0]['areacode'];
        }
        //获取新版本
        foreach ($orderInfo[0]['rooms'] as $room) {
            foreach ($room['user'] as &$userItem) {  
                if ($version >= '2.0.01') {

                    if ($version >= '2.0.11') {

                        if ($version >= '2.0.13') {
                             $userItem = array(
                                'name' => $userItem['name'],
                                'areaCode' => $userItem['areacode'],
                                'mobile' => $userItem['mobile'],
                                'identity' => $userItem['identity'],
                                'idsex' => $userItem['idsex'],
                                'idnation' => $userItem['idnation'],
                                'idaddress' => $userItem['idaddress'],
                                'orderUser' => $userItem['orderuser_id'],
                                'isdelete' => $userItem['isdelete'],
                            );
                        } else {
                            $userItem = array(
                                'name' => $userItem['name'],
                                'areaCode' => $userItem['areacode'],
                                'mobile' => $userItem['mobile'],
                                'identity' => $userItem['identity'],
                                'orderUser' => $userItem['orderuser_id'],
                                'isdelete' => $userItem['isdelete'],
                            );
                        }
                    } else {
                        $userItem = array(
                            'name' => $userItem['name'],
                            'mobile' => $userItem['mobile'],
                            'identity' => $userItem['identity'],
                            'orderUser' => $userItem['orderuser_id'],
                            'isdelete' => $userItem['isdelete'],
                        );
                     }
                } else {
                    $userItem = array(
                        'name' => $userItem['name'],
                        'mobile' => $userItem['mobile'],
                        'identity' => $userItem['identity'],
                    );
                }              
            }
            unset($userItem);          

            $subOrderItem = array(
                'order' => $room['id'],
                'starttime' => $room['startdate'],
                'endtime' => $room['enddate'],
                'checkouttime' => $room['checkoutdate'],
                'start' => date('Y-m-d', strtotime($room['startdate'])),
                'end' => date('Y-m-d', strtotime($room['checkoutdate'])),
                'endDate' => date('Y-m-d', strtotime($room['enddate'])),
                'night' => $room['night'],
                'realnight' => $room['realnight'],
                'hour' => $room['hour'],
                'status' => $room['status'],
                'statusName' => $orderLogic->statusMap[LANG_SET][$room['status']],
                'roomName' => $room['roominfo_name'],
                'roomType' => $room['roomtype_name'],
                'roomId' => $room['roominfo_id'],
                'pay' => $room['payment'],
                'minusPrice' => $room['minusprice'],
            );
            if ($version >= '2.0.00') {
                $subOrderItem['realnight'] = $room['realnight'];
            }
            //  版本v2.0.01 同住人需求改变传参结构,返回多个同住人
            if ($version >= '2.0.01') {
               $subOrderItem['users'] = $room['user'];
            } else {
               $subOrderItem['users'] = array($room['user'][0]);
            }

            $data['rooms'][] = $subOrderItem;
        }

        $otherCostPrice = 0;
        // v2.0.08增加 返回支付历史信息
        if ($version >= '2.0.08') {
            $payHistoryArrays = array(
                'received' => 0.00,
                'receivedDeposit' => 0.00,
                'refund' => 0.00,
                'refundDeposit' => 0.00,
            );
            // 计算各种金额总额 0:收款 1：押金 2：退款 3：退押金
            foreach ($orderInfo[0]['payHistory'] as $key => $orderInfoItem) {
                foreach ($orderInfoItem as $key => $payInfoItem) {
                    switch ($payInfoItem['type']) {
                        case 0:
                            $payHistoryArrays['received'] += $payInfoItem['pay'];
                            break;
                        case 1:
                            $payHistoryArrays['receivedDeposit'] += $payInfoItem['pay'];
                            break;
                        case 2:
                            $payHistoryArrays['refund'] += $payInfoItem['pay'];
                            break;
                        case 3:
                            $payHistoryArrays['refundDeposit'] += $payInfoItem['pay'];
                            break;
                        default;
                            // 加上已收的其他消费
                            if ($payInfoItem['hotelPayId'] != 0 && !in_array($payInfoItem['type'], [0,1,2,3])) {
                                $payHistoryArrays['received'] += $payInfoItem['pay'];
                            }
                            $otherCostPrice += $payInfoItem['pay'];
                            break;
                    }
                }
                unset($payInfoItem);
            }
            unset($orderInfoItem);

            $data['payHistory'] = $payHistoryArrays;
            $data['refundPrice'] = $orderInfo[0]['refundPrice'];
            $data['refundDeposit'] = $orderInfo[0]['refundDeposit'];
        }

        if ($version < '2.0.18') {
            // 旧版本  其他消费金额(含待收) 加到订单金额里面
            $data['rooms'][0]['pay'] += $otherCostPrice;
        }

        returnJson(200, 200, $data);
    }

    /**
     * @description 获取收款记录
     * @modify songanwei 2016-01-23
     * @modify wenhui 2017-03-02 返回退款记录v2.0.05
     * @for v1.0.0 ios
     */
    public function payHistory() {
        $params = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'hotel' => 'notnull,notempty,id',
            'order' => 'notnull,notempty,id',
        );
        $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);
        $userId = $params['userId'];
        $token = $params['token'];
        $hotelId = $params['hotel'];
        $version = getVersion(array('2.0.18','2.0.08'));

        //检验token
        $this->checkMobileToken($userId, $token);
        $orderInfoId = $params['order'];
        $orderLogic = A('Common/Order', 'Logic');
        try {
            if ($version >= '2.0.08') {
                $payHistorys = $orderLogic->getPayHistory($hotelId, $orderInfoId, true);
            } else {
                $payHistorys = $orderLogic->getPayHistory($hotelId, $orderInfoId);
            }
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }

        $data = array();
        foreach ($payHistorys as $payHistory) {

            if ($version < '2.0.18') {
                // 旧版本  其他消费已收金额 type 改为 0
                if ($payHistory['hotelpay_id'] != 0 && !in_array($payHistory['type'], [0,1,2,3])) {
                    $payHistory['type'] = 0;
                }
            }

            $data[] = array(
                'name' => $payHistory['name'],
                'type' => $payHistory['type'],
                'pay' => $payHistory['pay'],
                'time' => $payHistory['createtime'],
                'hotelPayId' => $payHistory['hotelpay_id'],
                'currencyId' => $payHistory['currency_id'],
                'transBeforePay' => $payHistory['trans_before_pay'],
                'symbol' => $payHistory['symbol'],
            );
        }
        returnJson(200, 200, $data);
    }

    /**
     * @description 录入订单
     * @modify songanwei 2016-01-23
     * @for v1.0.0
     */
    public function book() {
        $this->addOrder(1);
    }

    /**
     * @description 直接入住
     * @modify songanwei 2016-01-23
     * @for v1.0.0
     */
    public function bookAndCheckin() {
        $this->addOrder(2);
    }

    /**
     * @description 补录订单
     * @modify songanwei 2016-01-23
     * @for v1.0.0  ios
     */
    public function add() {
        $this->addOrder(3);
    }

    /**
     * @description 修改订单
     * @modify songanwei 2016-01-23
     * @for v1.0.1  ios
     */
    public function edit() {
        $params = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'hotel' => 'notnull,notempty,id',
            'order' => 'notnull,notempty,id',
            'channel' => 'notnull,notempty,id',
            'remark' => 'notnull,nameLength255',
            'detail' => 'notnull,notempty',
            'receive' => 'notnull,notempty',
        );           
        $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);
        $orderRecord = json_decode(stripslashes(htmlspecialchars_decode($params['detail'])), true);         
        // v2.0.01版本的参数校验
        $version = getVersion(array('2.0.19','2.0.13','2.0.11','2.0.05','2.0.01'));
        if ($version >= '2.0.01') {
            $validateRule = array(
                'orderRoomId' => 'id',
                'orderDate' => 'notnull,notempty',
                'roomId' => 'notnull,notempty,id',
                'nights' => 'notnull,notempty,natureNumber',
                'payment' => 'notnull,notempty,decimal8_2',
                'users'  => 'notnull,notempty',
                'hour'  => 'notempty,natureNumber',   
            );
            /*if ($version >= '2.0.11') {
                $validateUserRule = array(
                    'orderUser' => 'id',
                    'name' => 'notnull,notempty,nameLength20',               
                );
            } else {
                $validateUserRule = array(
                    'orderUser' => 'id',
                    'name' => 'notnull,notempty,nameLength20',
                    'identity' => 'IDCard',
                );
            }*/

            $validateUserRule = array(
                'orderUser' => 'id',
                'name' => 'notnull,notempty,nameLength20',
                'identity' => 'IDCard',
            );
            
            //子管理员修改订单（没有查看联系方式权限会显示****的问题）
            $mobileVersion = C('MOBILE_VERSION');
            if($version<$mobileVersion['mobile_change']){
                $validateUserRule = array_merge($validateUserRule,['mobile'=>'notempty,mobile']);
            }
            $orderUserModel = D('OrderUser');
            $orderUserInfo = $orderUserModel->getInfoByOrder($params['order']);
            $orderUserInfo = getArrayValueAsIndex($orderUserInfo, 'id');
            foreach ($orderRecord as &$orderRecordItem) {
                $this->ajaxValidateReturn($this->validateUtil, $orderRecordItem, $validateRule);             
                foreach ($orderRecordItem['users'] as &$orderUserItem) {
                    if (empty($orderUserItem['identity'])) {
                        unset($validateUserRule['identity']);
                    }

                    $this->ajaxValidateReturn($this->validateUtil, $orderUserItem, $validateUserRule);
                    $orderUserItem['orderUser'] = (!isset($orderUserItem['orderUser']) || empty($orderUserItem['orderUser'])) ? 0 : $orderUserItem['orderUser'];
                    //子管理员修改订单（没有查看联系方式权限会显示****的问题）
                    $oldMobile = '';
                    $oldidentity = '';
                    $oldidsex = '';
                    $oldidnation = '';
                    $oldidaddress = '';
                    if(!empty($orderUserItem['orderUser'])&&isset($orderUserInfo[$orderUserItem['orderUser']])){
                            $oldMobile = $orderUserInfo[$orderUserItem['orderUser']]['mobile'];
                            $oldidentity = $orderUserInfo[$orderUserItem['orderUser']]['identity'];
                            $oldidsex = $orderUserInfo[$orderUserItem['orderUser']]['idsex'];
                            $oldidnation = $orderUserInfo[$orderUserItem['orderUser']]['idnation'];
                            $oldidaddress = $orderUserInfo[$orderUserItem['orderUser']]['idaddress'];
                    }

                    $orderUserItem['mobile'] = isset($orderUserItem['mobile']) ? $orderUserItem['mobile'] : $oldMobile;
                    $orderUserItem['identity'] = isset($orderUserItem['identity']) ? $orderUserItem['identity'] : $oldidentity;
                    // v2.0.13 添加身份证数据
                    if ($version >= '2.0.13') {
                        $orderUserItem['idsex'] = isset($orderUserItem['idsex']) ? $orderUserItem['idsex'] : $oldidsex;
                        $orderUserItem['idnation'] = isset($orderUserItem['idnation']) ? $orderUserItem['idnation'] : $oldidnation;
                        $orderUserItem['idaddress'] = isset($orderUserItem['idaddress']) ? $orderUserItem['idaddress'] : $oldidaddress;
                    }

                    if($version>=$mobileVersion['mobile_change']){
                        // v2.0.11的参数校验 支持国际号码校验 新增参数 $orderUserItem['areaCode']
                        if ($version >= '2.0.11') {
                            if(isset($orderUserItem['mobile']) && !empty($orderUserItem['mobile'])){
                                $orderUserItem['areacode'] = isset($orderUserItem['areaCode']) ? $orderUserItem['areaCode'] : '86';
                                if (isset($orderUserItem['areaCode'])) unset($orderUserItem['areaCode']);

                                $this->ajaxValidateReturn($this->validateUtil, $orderUserItem['mobile'], 'globalMobile',
                                        array('globalMobile' => array('function', 'checkGlobalMobile,' . $orderUserItem['areacode'], '403,130,error'),
                                    ));
                            }
                        } else {
                            if(isset($orderUserItem['mobile']) && $orderUserItem['mobile'] !== ''){
                                $this->ajaxValidateReturn($this->validateUtil, $orderUserItem['mobile'], 'notempty,mobile');
                            }
                        }
                    }
                }
                if (isset($orderUserItem['month'])) {
                    $orderUserItem['nights'] = getNight($orderUserItem['orderDate'], date('Y-m-d',strtotime('+' . $orderUserItem['month'] . 'months', strtotime($orderUserItem['orderDate']))));
                }
                unset($orderUserItem);
                $orderRecordItem['orderRoomId'] = (!isset($orderRecordItem['orderRoomId']) || empty($orderRecordItem['orderRoomId'])) ? 0 : $orderRecordItem['orderRoomId'];
            }
            unset($orderRecordItem);
        } else {
            $validateRule = array(
                'orderRoomId' => 'id',
                'name' => 'notnull,notempty,nameLength20',
                'mobile' => 'mobile',
                'identity' => 'IDCard',
                'orderDate' => 'notnull,notempty,isDate',
                'roomId' => 'notnull,notempty,id',
                'nights' => 'notnull,notempty,natureNumber',
                'payment' => 'notnull,notempty,decimal8_2',
            );
            foreach ($orderRecord as &$orderRecordItem) {
                $this->ajaxValidateReturn($this->validateUtil, $orderRecordItem, $validateRule);
                $orderRecordItem['orderRoomId'] = isset($orderRecordItem['orderRoomId']) ? $orderRecordItem['orderRoomId'] : 0;

                // 移动端添加订单只可能添加一个同住人,先格式化添加订单的数据格式
                if ($orderRecordItem['orderRoomId'] == 0) {
                    $orderRecordItem['users'] = array(array(
                        'orderUser' => 0,
                        'name' => $orderRecordItem['name'],
                        'mobile' => isset($orderRecordItem['mobile']) ? $orderRecordItem['mobile'] : '',
                        'identity' => isset($orderRecordItem['identity']) ? $orderRecordItem['identity'] : '',
                    ));
                }
            }       
            unset($orderRecordItem);
        }

        $receives = json_decode(stripslashes(htmlspecialchars_decode($params['receive'])), true);
        $validateRule = array(
            'category' => 'notnull,notempty',
            'type' => 'notnull,notempty,id',
            'value' => 'notnull,notempty,decimal8_2',
        );
        if ($version >= '2.0.19') {
            $validateRule['transCurrencyId'] = 'notnull,notempty,id';
        }
        foreach ($receives as $receive) {
            $this->ajaxValidateReturn($this->validateUtil, $receive, $validateRule);
        }
        
        $userId = $params['userId'];
        $token = $params['token'];
        $hotelChannelId = $params['channel']; //来源渠道
        $hotelId = $params['hotel'];     //客栈ID
        $orderId = $params['order']; //订单ID
        $remark = $params['remark']; //备注
        //检查token
        $this->checkMobileToken($userId, $token);
        // 检查父订单ID是否在客栈内
        $orderLogic = A('Common/Order', 'Logic');
        $orderInHotel = $orderLogic->checkOrderInHotel($hotelId, $orderId);
        if (!$orderInHotel) {
            returnJson(403, 202);
            return;
        }
          
        // 检查子订单ID(s)是否在客栈内
        $subOrderIds = array_unique(array_column($orderRecord, 'orderRoomId'));
        $subOrderIds = array_values(array_diff($subOrderIds, array(0)));
        $orderInHotel = $orderLogic->checkSubOrderInHotel($subOrderIds, $hotelId);
        if (!$orderInHotel) {
            returnJson(403, 202);
            return;
        }
        
        // 检查房间是否在客栈内
        $roomLogic = A('Common/Room', 'Logic');
        $roomInHotel = $roomLogic->checkRoomInHotel($hotelId, array_column($orderRecord, 'roomId'));
        if (!$roomInHotel) {
            returnJson(403, 202);
            return;
        }

        // 取出默认货币
        $currencyLogic = A('Common/Currency', 'Logic');
        $hotelDefaultCurrency = $currencyLogic->takeHotelCurrency($hotelId, true);
        $currencyId = !empty($hotelDefaultCurrency) ? $hotelDefaultCurrency[0]['currencyId'] : 8 ; // 8 = 人民币

        $deposit = 0.00; //押金
        $receipt = 0.00; //已收金额
        //计算总额
        foreach ($receives as $index => &$receive) {
            $isTrans = false;
            $receive['transBeforeValue'] = $receive['value'];
            if ($version >= '2.0.19') {
                if ($currencyId != $receive['transCurrencyId'] && (double) $receive['value'] != 0) {
                    $isTrans = true;
                }
            } else {
                $receive['transCurrencyId'] = $currencyId;
            }

            if ($receive['category'] == 1) {
                // 价格汇率转换
                if ($isTrans) {
                    $receive['value'] = $currencyLogic->exchangeRates($receive['transCurrencyId'], $currencyId, $receive['value']);
                }

                $deposit+= $receive['value'];
            } else if ($receive['category'] == 0) {
                // 价格汇率转换
                if ($isTrans) {
                    $receive['value'] = $currencyLogic->exchangeRates($receive['transCurrencyId'], $currencyId, $receive['value']);
                }

                $receipt+= $receive['value'];
            } else if ($receive['type'] != 0) {
                // 价格汇率转换
                if ($isTrans) {
                    $receive['value'] = $currencyLogic->exchangeRates($receive['transCurrencyId'], $currencyId, $receive['value']);
                }

                // 其他消费 （不含待收款）
                $receipt+= $receive['value'];
            } else if ($receive['type'] == 0) {
                // 带收款 价格汇率转换
                if ($isTrans) {
                    $receive['value'] = $currencyLogic->exchangeRates($receive['transCurrencyId'], $currencyId, $receive['value']);
                }
            }

            //过滤数据
            if ((double) $receive['value'] == 0) {
                unset($receives[$index]);
            }
        }

        if ($version < '2.0.01') {
            try {
                $subOrders = $orderLogic->getOrderInfo($hotelId, array($orderId));
            } catch (\Exception $e) {
                returnJson($e->getMessage());
                return;
            }
            $subOrders = getArrayValueAsIndex($subOrders[0]['rooms'], 'id');
            // 为订单补充同住人信息,第一个保留前端传过来的,其他还原成数据库里的
            foreach ($orderRecord as &$orderRecordItem) {
                if ($orderRecordItem['orderRoomId'] == 0) {
                    continue;
                }

                if (isset($subOrders[$orderRecordItem['orderRoomId']])) {
                    $orderRecordItem['users'] = array();
                    foreach ($subOrders[$orderRecordItem['orderRoomId']]['user'] as $index => $orderUserItem) {
                        if ($index == 0) {
                            array_push($orderRecordItem['users'], array(
                                'orderUser' => $orderUserItem['orderuser_id'],
                                'name' => $orderRecordItem['name'],
                                'mobile' => isset($orderRecordItem['mobile']) ? $orderRecordItem['mobile'] : '',
                                'identity' => isset($orderRecordItem['identity']) ? $orderRecordItem['identity'] : '',
                            ));
                        } else {
                            array_push($orderRecordItem['users'], array(
                                'orderUser' => $orderUserItem['orderuser_id'],
                                'name' => $orderUserItem['name'],
                                'mobile' => $orderUserItem['mobile'],
                                'identity' => $orderUserItem['identity'],
                            ));
                        }
                    }
                    unset($orderUserItem);
                }
            }
            unset($orderRecordItem);      
        }
        
        //判断订单状态
        try {         
           $orderLogic->saveInfo($hotelId, $orderId, $hotelChannelId, $deposit, $receipt, $remark, $orderRecord, $receives, ORDER_CHANGE_APP);         
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }
        returnJson(200, 200, 'success');
    }

    /**
     * @description 取消订单
     * @modify songanwei 2016-01-23
     * @for v1.0.0   ios
     */
    public function cancel() {
        $param = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'hotel' => 'notnull,notempty,id',
            'order' => 'notnull,notempty,id',
            'suborder' => 'notnull,notempty,id',
            'receipt' => 'notempty,decimal8_2',
            'receiptPay' => 'notempty,id',
            'deposit' => 'notempty,decimal8_2',
            'depositPay' => 'notempty,id',
            'remark' => 'notnull,orderRemark',
        );

        // v2.0.19 多币种
        $version = getVersion(array('2.0.19'));
        if ($version >= '2.0.19') {
            $validateRule['receiptCurrencyId'] = 'notempty,id';
            $validateRule['depositCurrencyId'] = 'notempty,id';
        }

        $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);

        $hotelId = $param['hotel'];
        $userId = $param['userId'];
        $token = $param['token'];
        $orderId = $param['order'];
        $deposit = $param['deposit'];
        $receipt = $param['receipt'];
        $depositPay = $param['depositPay'];
        $receiptPay = $param['receiptPay'];
        $receiptCurrencyId = isset($param['receiptCurrencyId']) ? $param['receiptCurrencyId'] : 0;
        $depositCurrencyId = isset($param['depositCurrencyId']) ? $param['depositCurrencyId'] : 0;
        if ($receipt == 0) {
            $receipt = null;
        }
        if ($deposit >= 0) {
            $deposit = null;
        }

        // v2.0.19 多币种
        if ($version >= '2.0.19') {
            // 取出默认货币
            $currencyLogic = A('Common/Currency', 'Logic');
            $hotelDefaultCurrency = $currencyLogic->takeHotelCurrency($hotelId, true);
            $currencyId = !empty($hotelDefaultCurrency) ? $hotelDefaultCurrency[0]['currencyId'] : 8 ; // 8 = 人民币

            // 价格汇率转换
            $receiptBeforeValue = !is_null($receipt) ? $receipt : 0;
            $depositBeforeValue = !is_null($deposit) ? $deposit : 0;
            if (isset($param['receiptCurrencyId']) && !is_null($receipt) && $currencyId != $receiptCurrencyId) {
                $receipt = $currencyLogic->exchangeRates($receiptCurrencyId, $currencyId, $receipt);
            }
            if (isset($param['depositCurrencyId']) && !is_null($deposit) && $currencyId != $depositCurrencyId) {
                $deposit = $currencyLogic->exchangeRates($depositCurrencyId, $currencyId, $deposit);
            }
        }

        //验证token
        $this->checkMobileToken($userId, $token);

        $remark = $param['remark'];
        $subOrderIds = array($param['suborder']);
        $orderLogic = A('Common/Order', 'Logic');

        try {
            $result = $orderLogic->cancelOrder($hotelId, $orderId, $subOrderIds, ORDER_CHANGE_APP, $deposit, $depositPay, $receipt, $receiptPay, $remark, null, false, $receiptBeforeValue, $depositBeforeValue, $receiptCurrencyId, $depositCurrencyId);
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }
        if (!$result) {
            return;
        }

        returnJson(200, 200, 'success');
    }

    /**
     * 退房ajax接口
     * @modify trainyao 2016-01-06    创建
     */
    public function checkout() {
        $param = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'hotel' => 'notnull,notempty,id',
            'order' => 'notnull,notempty,id',
            'suborder' => 'notnull,notempty,concatId',
            'receipt' => 'notempty,decimal8_2',
            'receiptPay' => 'notempty,id',
            'deposit' => 'notempty,decimal8_2',
            'depositPay' => 'notempty,id',
            'remark' => 'notnull,orderRemark',
        );

        // v2.0.19 多币种
        $version = getVersion(array('2.0.19'));
        if ($version >= '2.0.19') {
            $validateRule['receiptCurrencyId'] = 'notempty,id';
            $validateRule['depositCurrencyId'] = 'notempty,id';
        }

        $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        $userId = $param['userId'];
        $token = $param['token'];
        $hotelId = $param['hotel'];
        $orderId = $param['order'];
        $subOrderIds = explode(',', $param['suborder']);
        $deposit = $param['deposit'];
        $receipt = $param['receipt'];
        $depositPay = $param['depositPay'];
        $receiptPay = $param['receiptPay'];
        $remark = $param['remark'];
        $receiptCurrencyId = isset($param['receiptCurrencyId']) ? $param['receiptCurrencyId'] : 0;
        $depositCurrencyId = isset($param['depositCurrencyId']) ? $param['depositCurrencyId'] : 0;
        if ($receipt == 0) {
            $receipt = null;
        }
        if ($deposit >= 0) {
            $deposit = null;
        }

        // v2.0.19 多币种
        if ($version >= '2.0.19') {
            // 取出默认货币
            $currencyLogic = A('Common/Currency', 'Logic');
            $hotelDefaultCurrency = $currencyLogic->takeHotelCurrency($hotelId, true);
            $currencyId = !empty($hotelDefaultCurrency) ? $hotelDefaultCurrency[0]['currencyId'] : 8 ; // 8 = 人民币

            // 价格汇率转换
            $receiptBeforeValue = !is_null($receipt) ? $receipt : 0;
            $depositBeforeValue = !is_null($deposit) ? $deposit : 0;
            if (isset($param['receiptCurrencyId']) && !is_null($receipt) && $currencyId != $receiptCurrencyId) {
                $receipt = $currencyLogic->exchangeRates($receiptCurrencyId, $currencyId, $receipt);
            }
            if (isset($param['depositCurrencyId']) && !is_null($deposit) && $currencyId != $depositCurrencyId) {
                $deposit = $currencyLogic->exchangeRates($depositCurrencyId, $currencyId, $deposit);
            }
        }

        //token验证
        $this->checkMobileToken($userId, $token);
        $orderLogic = A('Common/Order', 'Logic');

        try {
            $orderLogic->checkOutOrder($hotelId, $orderId, $subOrderIds, ORDER_CHANGE_APP, $subOrderIds, $receipt, $receiptPay, $deposit, $depositPay, $remark, null, false, $receiptBeforeValue, $depositBeforeValue, $receiptCurrencyId, $depositCurrencyId);
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }
        returnJson(200, 200, 'success');
    }
    /**
     * 办理入住ajax接口
     * @modify trainyao 2016-01-07    创建
     */
    public function checkin() {
        $param = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'hotel' => 'notnull,notempty,id',
            'order' => 'notnull,notempty,id',
            'data' => 'notnull,notempty',
            // 可空参数
            'receipt' => 'notempty,decimal8_2',
            'receiptPay' => 'notempty,id',
            'deposit' => 'notempty,decimal8_2',
            'depositPay' => 'notempty,id',
            'remark' => 'notnull,nameLength255',
        );

        // v2.0.01参数校验 取数组第一个子订单办理入住 ,支持传多个同住人
        $version = getVersion(array('2.0.19','2.0.13','2.0.11','2.0.05','2.0.02', '2.0.01', '2.0.00'));

        if ($version >= '2.0.19') {
            $validateRule['receiptCurrencyId'] = 'notempty,id';
            $validateRule['depositCurrencyId'] = 'notempty,id';
        }

        $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        $orderRoomData = json_decode(stripslashes(htmlspecialchars_decode($param['data'])), true);
        
        // 2.0.00版本后只取数组第一个子订单办理入住
        if ($version >= '2.0.00') {
            $orderRoomData = array($orderRoomData[0]);
        }
        if ($version >= '2.0.01') {
            $validateRule = array(
                'suborder' => 'notnull,notempty,id',
                'roomId'   => 'notempty,id',
                'nights'   => 'notempty,id,natureNumber',
                'payment'  => 'notempty,decimal8_2',
                'users'    => 'notnull,notempty', 
                'hour'  => 'notempty,natureNumber',     
            );
            if ($version >= '2.0.11') {
                $validateUserRule = array(
                    'orderUser' => 'notnull,notempty',
                    'name'      => 'notnull,notempty,nameLength20',
                    'identity'  => 'notempty',
                );
                if ($version >= '2.0.13') {
                    $validateUserRule['identity'] = 'IDCard';
                }
            } else {
                $validateUserRule = array(
                    'orderUser' => 'notnull,notempty',
                    'name'      => 'notnull,notempty,nameLength20',
                    'identity'  => 'notempty,IDCard',
                );
            }

            $orderUserModel = D('OrderUser');
            $orderUserInfo = $orderUserModel->getInfoByOrder($param['order']);
            $orderUserInfo = getArrayValueAsIndex($orderUserInfo, 'id');
            $mobileVersion = C('MOBILE_VERSION');
            //子管理员修改订单（没有查看联系方式权限会显示****的问题）
            if($version<$mobileVersion['mobile_change']){
                // v2.0.11的参数校验 支持国际号码校验
                if ($version >= '2.0.11') { 
                    $validateUserRule = array_merge($validateUserRule,['mobile'=>'notempty']);
                } else {
                    $validateUserRule = array_merge($validateUserRule,['mobile'=>'notempty,mobile']);
                }
            }
            foreach ($orderRoomData as &$orderRoomItem) {
                $validateResult = $this->ajaxValidateReturn($this->validateUtil, $orderRoomItem, $validateRule);
                if (!$validateResult) {
                    return;
                }
                $orderRoomItem['value'] = $orderRoomItem['suborder'];
                foreach ($orderRoomItem['users'] as &$orderUserItem) {
                    $validateResult = $this->ajaxValidateReturn($this->validateUtil, $orderUserItem, $validateUserRule);
                    if (!$validateResult) {
                        return;
                    }
                    //子管理员修改订单（没有查看联系方式权限会显示****的问题）
                    $oldMobile = '';
                    $oldidentity = '';
                    $oldidsex = '';
                    $oldidnation = '';
                    $oldidaddress = '';
                    if(!empty($orderUserItem['orderUser'])&&isset($orderUserInfo[$orderUserItem['orderUser']])){
                            $oldMobile = $orderUserInfo[$orderUserItem['orderUser']]['mobile'];
                            $oldidentity = $orderUserInfo[$orderUserItem['orderUser']]['identity'];
                            $oldidsex = $orderUserInfo[$orderUserItem['orderUser']]['idsex'];
                            $oldidnation = $orderUserInfo[$orderUserItem['orderUser']]['idnation'];
                            $oldidaddress = $orderUserInfo[$orderUserItem['orderUser']]['idaddress'];
                    }
                    $orderUserItem['mobile'] = isset($orderUserItem['mobile']) ? $orderUserItem['mobile'] : $oldMobile;
                    $orderUserItem['identity'] = isset($orderUserItem['identity']) ? $orderUserItem['identity']: $oldidentity;
                    // v2.0.13 添加身份证数据
                    if ($version >= '2.0.13') {
                        $orderUserItem['idsex'] = isset($orderUserItem['idsex']) ? $orderUserItem['idsex'] : $oldidsex;
                        $orderUserItem['idnation'] = isset($orderUserItem['idnation']) ? $orderUserItem['idnation'] : $oldidnation;
                        $orderUserItem['idaddress'] = isset($orderUserItem['idaddress']) ? $orderUserItem['idaddress'] : $oldidaddress;
                    }

                    if($version>=$mobileVersion['mobile_change']){
                        // v2.0.11的参数校验 支持国际号码校验 新增 $orderUserItem['areaCode']
                        if ($version >= '2.0.11') {
                            $orderUserItem['areacode'] = isset($orderUserItem['areaCode']) ? $orderUserItem['areaCode'] : '86';
                            if (isset($orderUserItem['areaCode'])) unset($orderUserItem['areaCode']);

                            if(isset($orderUserItem['mobile']) && !empty($orderUserItem['mobile'])){
                                    $this->ajaxValidateReturn($this->validateUtil, $orderUserItem['mobile'], 'globalMobile',
                                            array('globalMobile' => array('function', 'checkGlobalMobile,' . $orderUserItem['areacode'], '403,130,error'),
                                        ));
                            }
                        } else {
                            if(isset($orderUserItem['mobile']) && $orderUserItem['mobile'] !== ''){
                                $this->ajaxValidateReturn($this->validateUtil, $orderUserItem['mobile'], 'notempty,mobile');
                            }
                        }   
                    }
                }
                unset($orderUserItem);
            }
            unset($orderRoomItem);
        } else {
            $validateRule = array(
                'suborder' => 'notnull,notempty,id',
                'name' => 'notnull,notempty,nameLength20',
                'mobile' => 'notempty,mobile',
                'identity' => 'notempty,IDCard',
                'nights' => 'notempty,id',
                'payment' => 'notempty,decimal8_2',
                'roomId' => 'notempty,id',
            );
            foreach ($orderRoomData as $key => $orderRoom) {
                $this->ajaxValidateReturn($this->validateUtil, $orderRoom, $validateRule);
                $orderRoomData[$key]['mobile'] = isset($orderRoom['mobile']) ? $orderRoom['mobile'] : '';
            }
            unset($orderRoom);
        }
        $userId = $param['userId'];
        $token = $param['token'];
        $hotelId = $param['hotel'];
        $orderId = $param['order'];
        $subOrderIds = array_column($orderRoomData, 'suborder');
        $receipt = $param['receipt'];
        $receiptPay = $param['receiptPay'];
        $deposit = $param['deposit'];
        $depositPay = $param['depositPay'];
        $remark = $param['remark'];
        $checkIn = isset($param['checkIn']) ? $param['checkIn'] : 0;
        $receiptCurrencyId = isset($param['receiptCurrencyId']) ? $param['receiptCurrencyId'] : 0;
        $depositCurrencyId = isset($param['depositCurrencyId']) ? $param['depositCurrencyId'] : 0;

        if ($receipt <= 0) {
            $receipt = null;
            $receiptPay = null;
        }
        if ($deposit <= 0) {
            $deposit = null;
            $depositPay = null;
        }

        $this->checkMobileToken($userId, $token);

        $orderLogic = A('Common/Order', 'Logic');
        if ($version < '2.0.01') {
            // 为订单补充同住人信息,第一个保留前端传过来的,其他还原成数据库里的
            try {
                $subOrders = $orderLogic->getOrderInfo($hotelId, array($orderId));
            } catch (\Exception $e) {
                returnJson($e->getMessage());
                return;
            }
            $subOrders = getArrayValueAsIndex($subOrders[0]['rooms'], 'id');
            // 处理传入参数
            foreach ($orderRoomData as &$orderRoomItem) {
                $orderRoomItem['value'] = $orderRoomItem['suborder'];
                unset($orderRoomItem['suborder']);

                if (isset($subOrders[$orderRoomItem['value']])) {
                    $orderRoomItem['users'] = array();
                    foreach ($subOrders[$orderRoomItem['value']]['user'] as $index => $orderUserItem) {
                        // 已删除的同住人不提交
                        if ($orderUserItem['isdelete'] == IS_DELETE) {
                            continue;
                        }

                        if ($index == 0) {
                            array_push($orderRoomItem['users'], array(
                                'orderUser' => $orderUserItem['orderuser_id'],
                                'name' => $orderRoomItem['name'],
                                'mobile' => isset($orderRoomItem['mobile']) ? $orderRoomItem['mobile'] : '',
                                'identity' => isset($orderRoomItem['identity']) ? $orderRoomItem['identity'] : '',
                            ));
                        } else {
                            array_push($orderRoomItem['users'], array(
                                'orderUser' => $orderUserItem['orderuser_id'],
                                'name' => $orderUserItem['name'],
                                'mobile' => $orderUserItem['mobile'],
                                'identity' => $orderUserItem['identity'],
                            ));
                        }
                    }
                    unset($orderUserItem);
                }
            }
            unset($orderRoomItem);
            
        }

        // v2.0.02增加判断是否检查当天之前的房间状态 即是否脏房、已预订或已入住 检查并返回数据
        if ($version >= '2.0.02' && $checkIn == 1) {
            // 办理入住时 移动端一个一个办理 只需要一个roomId
            $roomId = $orderRoomData['0']['roomId'];
            // orderRoom表的Id 获取订单时间
            $orderRoomId = $orderRoomData['0']['value'];
            // 获取该房间当天之前已预订或已入住的房间信息
            try {
                $dirtyData = $orderLogic->checkInOrder($hotelId, $orderId, $subOrderIds, ORDER_CHANGE_WEB, $orderRoomData, $receipt, $receiptPay, $deposit, $depositPay, $remark, null, $checkIn, $roomId, $orderRoomId);
            } catch (\Exception $e) {
                returnJson($e->getMessage());
                return;
            }

            //返回查询数据信息
            if (!empty($dirtyData)) {
                returnJson(403, 308, $dirtyData);
            }
        }

        // 多币种
        if ($version >= '2.0.19') {
            // 取出默认货币
            $currencyLogic = A('Common/Currency', 'Logic');
            $hotelDefaultCurrency = $currencyLogic->takeHotelCurrency($hotelId, true);
            $currencyId = !empty($hotelDefaultCurrency) ? $hotelDefaultCurrency[0]['currencyId'] : 8 ; // 8 = 人民币

            // 价格汇率转换
            $receiptBeforeValue = !is_null($receipt) ? $receipt : 0;
            $depositBeforeValue = !is_null($deposit) ? $deposit : 0;
            if (isset($param['receiptCurrencyId']) && !is_null($receipt) && $currencyId != $receiptCurrencyId) {
                $receipt = $currencyLogic->exchangeRates($receiptCurrencyId, $currencyId, $receipt);
            }
            if (isset($param['depositCurrencyId']) && !is_null($deposit) && $currencyId != $depositCurrencyId) {
                $deposit = $currencyLogic->exchangeRates($depositCurrencyId, $currencyId, $deposit);
            }
        }

        try {
            $orderAfterCheckInData = $orderLogic->checkInOrder($hotelId, $orderId, $subOrderIds, ORDER_CHANGE_APP, $orderRoomData, $receipt, $receiptPay, $deposit, $depositPay, $remark, null, 0, '', '', $vipCard, $receiptBeforeValue, $depositBeforeValue, $receiptCurrencyId, $depositCurrencyId);
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }

        returnJson(200, 200, 'success');
    }

    /**
     * 添加订单
     * @modify songanwei 2016-01-23
     * @param integer $type  操作类型
     */
    private function addOrder($type) {
        $params = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'hotel' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'remark' => 'notnull,nameLength255',
            'channel' => 'notnull,notempty,id',
            'detail' => 'notnull,notempty',
            'receive' => 'notnull,notempty',
            'payment' => 'notnull,notempty,decimal',
        );
        $validateResult = $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);
        if (!$validateResult) {
            return;
        }
        // 检查子订单数据格式
        $orderRecord = json_decode(stripslashes(htmlspecialchars_decode($params['detail'])), true);
        if (!is_array($orderRecord)) {
            returnJson(403, 213);
            return;
        }
        
        $receives = json_decode(stripslashes(htmlspecialchars_decode($params['receive'])), true);
        if (!is_array($receives)) {
            returnJson(403, 213);
            return;
        }

        // v2.0.01的参数校验 支持传多个同住人
        $version = getVersion(array('2.0.19','2.0.17', '2.0.13','2.0.11', '2.0.02', '2.0.01'));
        if ($version >= '2.0.01') {
            $validateRule = array(
                'orderDate' => 'notnull,notempty',
                'roomId' => 'notnull,notempty,id',
                'nights' => 'notnull,notempty,natureNumber',
                'payment' => 'notnull,notempty,decimal',
                'users'  => 'notnull,notempty',  
                'hour'  => 'notempty,natureNumber',
                'month'  => 'notempty,natureNumber',
            );
            // v2.0.11的参数校验 支持国际号码校验
            if ($version >= '2.0.11') {
                $validateUserRule = array(
                    'name' => 'notnull,notempty,nameLength20',
                    //'identity' => 'IDCard',
                );
            } else {
                $validateUserRule = array(
                    'name' => 'notnull,notempty,nameLength20',
                    'mobile' => 'mobile',
                    'identity' => 'IDCard',
                );
            }
            foreach ($orderRecord as &$orderRecordItem) {
                $validateResult = $this->ajaxValidateReturn($this->validateUtil, $orderRecordItem, $validateRule);
                if (!$validateResult) {
                    return;
                    break;
                }
                $orderRecordItem['payment'] = $orderRecordItem['payment']  > 999999.99 ? 999999.99 : $orderRecordItem['payment'];
                if (isset($orderRecordItem['month'])) {
                    $orderRecordItem['nights'] = getNight($orderRecordItem['orderDate'], date('Y-m-d',strtotime('+' . $orderRecordItem['month'] . 'months', strtotime($orderRecordItem['orderDate']))));
                }
                foreach ($orderRecordItem['users'] as &$orderUserItem) {
                    if ($version >= '2.0.11' && isset($orderUserItem['identity']) && !empty($orderUserItem['identity'])) {
                        $validateUserRule['identity'] = 'IDCard';
                    }

                    $validateResult = $this->ajaxValidateReturn($this->validateUtil, $orderUserItem, $validateUserRule);
                    if (!$validateResult) {
                        return;
                        break; 
                    }

                    $orderUserItem['mobile'] = isset($orderUserItem['mobile']) ? $orderUserItem['mobile'] : '';
                    $orderUserItem['email'] = isset($orderUserItem['email']) ? $orderUserItem['email'] : '';

                    // v2.0.11的参数校验 支持国际号码校验
                    if ($version >= '2.0.11' && !empty($orderUserItem['mobile'])) {
                        $orderUserItem['areacode'] = isset($orderUserItem['areaCode']) ? $orderUserItem['areaCode'] : '86';
                        if (isset($orderUserItem['areaCode'])) unset($orderUserItem['areaCode']);
                        // 校验国际电话
                        $this->ajaxValidateReturn($this->validateUtil, $orderUserItem['mobile'], 'globalMobile',
                        array('globalMobile' => array('function', 'checkGlobalMobile,' . $orderUserItem['areacode'], '403,130,error'),
                        ));
                    }

                    // v2.0.13 添加身份证数据
                    if ($version >= '2.0.13') {
                        $orderUserItem['idsex'] = isset($orderUserItem['idsex']) ? $orderUserItem['idsex'] : '';
                        $orderUserItem['idnation'] = isset($orderUserItem['idnation']) ? $orderUserItem['idnation'] : '';
                        $orderUserItem['idaddress'] = isset($orderUserItem['idaddress']) ? $orderUserItem['idaddress'] : '';
                    }
                }
                unset($orderUserItem);
            }
            unset($orderRecordItem);
        } else {
            $validateRule = array(
                'orderDate' => 'notnull,notempty,isDate',
                'roomId' => 'notnull,notempty,id',
                'nights' => 'notnull,notempty,positiveInteger',
                'payment' => 'notnull,notempty,decimal',
                'name' => 'notnull,notempty,nameLength20',
                'mobile' => 'mobile',
                'identity' => 'IDCard',
            );
            foreach ($orderRecord as &$subOrder) {
                $validateResult = $this->ajaxValidateReturn($this->validateUtil, $subOrder, $validateRule);
                if (!$validateResult) {
                    return;
                    break;
                }
                $subOrder['payment'] = $subOrder['payment'] > 999999.99 ? 999999.99 : $subOrder['payment'];
                $subOrder['users'] = array(array(
                    'name' => $subOrder['name'],
                    'mobile' => isset($subOrder['mobile']) ? $subOrder['mobile'] : '',
                    'identity' => isset($subOrder['identity']) ? $subOrder['identity'] : '',
                ));
            }
            unset($subOrder);
        }

        $validateRule = array(
            'category' => 'notnull,notempty',
            'type' => 'notnull,notempty,id',
            'value' => 'notnull,notempty,decimal',
        );
        if ($version >= '2.0.19') {
            $validateRule['transCurrencyId'] = 'notnull,notempty,id';
        }
        foreach ($receives as $receive) {
            $validateResult = $this->ajaxValidateReturn($this->validateUtil, $receive, $validateRule);
            if (!$validateResult) {
                return;
                break;
            }
        }
        unset($receive);

        $hotelChannelId = $params['channel']; //来源渠道
        $hotelId = $params['hotel']; //客栈ID
        $payment = $params['payment']; //应付金额
        $remark = $params['remark']; //备注
        $userId = $params['userId'];
        $token = $params['token'];

        $checkIn = isset($params['checkIn']) ? $params['checkIn'] : 0;
        //检查参数
        $this->checkMobileToken($userId, $token);

        // 取出默认货币
        $currencyLogic = A('Common/Currency', 'Logic');
        $hotelDefaultCurrency = $currencyLogic->takeHotelCurrency($hotelId, true);
        $currencyId = !empty($hotelDefaultCurrency) ? $hotelDefaultCurrency[0]['currencyId'] : 8 ; // 8 = 人民币

        // 检查时间冲突
        $deposit = 0.00; //押金
        $receipt = 0.00; //已收金额
        //计算总额
        foreach ($receives as $index => &$receive) {
            // v2.0.19 美住多币种
            $isTrans = false;
            $receive['transBeforeValue'] = $receive['value'];
            if ($version >= '2.0.19') {
                if ($currencyId != $receive['transCurrencyId'] && (double) $receive['value'] != 0) {
                    $isTrans = true;
                }
            } else {
                $receive['transCurrencyId'] = $currencyId;
            }

            if ($receive['category'] == 1) {
                // 价格汇率转换
                if ($isTrans) {
                    $receive['value'] = $currencyLogic->exchangeRates($receive['transCurrencyId'], $currencyId, $receive['value']);
                }

                $deposit+= $receive['value'];
            } else if ($receive['category'] == 0) {
                // 价格汇率转换
                if ($isTrans) {
                    $receive['value'] = $currencyLogic->exchangeRates($receive['transCurrencyId'], $currencyId, $receive['value']);
                }

                $receipt+= $receive['value'];
            } else if ($receive['type'] != 0) {
                // 价格汇率转换
                if ($isTrans) {
                    $receive['value'] = $currencyLogic->exchangeRates($receive['transCurrencyId'], $currencyId, $receive['value']);
                }

                // 其他消费 （不含待收款）
                $receipt+= $receive['value'];
                // 订单金额加上 其他消费
                $payment += $receive['value'];
            } else if ($receive['type'] == 0) {
                // 带收款 价格汇率转换
                if ($isTrans) {
                    $receive['value'] = $currencyLogic->exchangeRates($receive['transCurrencyId'], $currencyId, $receive['value']);
                }
            }


            //过滤数据
            if ((double) $receive['value'] == 0) {
                unset($receives[$index]);
            }
        }
        //过滤数据
        $payment = $payment > 999999.99 ? 999999.99 : $payment;
        $payment = $payment < 0 ? 0 : $payment;
        $deposit = $deposit > 999999.99 ? 999999.99 : $deposit;
        $deposit = $deposit < 0 ? 0 : $deposit;
        $receipt = $receipt > 999999.99 ? 999999.99 : $receipt;
        $receipt = $receipt < 0 ? 0 : $receipt;
      
        $orderLogic = A('Common/Order', 'Logic');

        // v2.0.02 增加判断是否检查当天之前的房间状态 即是否脏房、已预订或已入住 检查并返回数据
        if ($version >= '2.0.02' && $type == 2 && $checkIn == 1) {
            //查询该房间当天之前已预订或已入住的房间信息 是否脏房
            try {
                    $dirtyData = $orderLogic->addInfo($hotelId, $hotelChannelId, $deposit, $payment, $receipt, $remark, $orderRecord, $receives, $type, ORDER_CHANGE_APP, false, $checkIn);
            } catch (\Exception $e) {
                    returnJson($e->getMessage());
                    return;
            }

            $roomId = array();
            foreach ($orderRecord as $roomItem) {
                array_push($roomId, $roomItem['roomId']);
            }
            unset($roomItem);

            if (!empty($dirtyData)) {
                //返回查询数据信息
                returnJson(403, 308, $dirtyData);
            }
        }
        //检查并添加数据
        try {
            $data = $orderLogic->addInfo($hotelId, $hotelChannelId, $deposit, $payment, $receipt, $remark, $orderRecord, $receives, $type, ORDER_CHANGE_APP, false, 0, 0, null, null, null, $version);
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }
        if (!$data) {
            return;
        }

        // 处理数据
        foreach ($data as &$subOrder) {
            $subOrder['channelName'] = $subOrder['channelname'];
            unset($subOrder['channelname']);
            $subOrder['suborder'] = $subOrder['id'];
            unset($subOrder['id']);
            $subOrder['roomId'] = $subOrder['room'];
            unset($subOrder['room']);
            $subOrder['roomType'] = $subOrder['roomtype'];
            unset($subOrder['roomtype']);
            $subOrder['roomName'] = $subOrder['roomname'];
            unset($subOrder['roomname']);
        }
        unset($subOrder);

        returnJson(200, 200, $data);
    }
    
        /**
     *  获取查询订单列表
     * @add Paddy 2016-11-21
     */
    public function search() {
        $params = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'hotel' => 'notnull,notempty,id',
            'token' => 'notnull,notempty'
        );
        $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);
        $userId = $params['userId'];
        $token = $params['token'];
        $hotelId = $params['hotel'];
    
        $this->checkMobileToken($userId, $token);

        $keywords = empty($params['keywords']) ? null : $params['keywords'];
        $pageIndex = (int) $params['pageIndex'];
        if ($pageIndex<1) {
            $pageIndex = 1;
        }
        $pageSize = (int) $params['pageSize'];
        if ($pageSize<1) {
            $pageSize = (int)C('PAGE_SIZE');
        }

        $type = isset($params['type']) ? $params['type'] : null;
        $statusType = isset($params['statusType']) ? $params['statusType'] : null;
        $startTime = isset($params['startTime']) ? strtotime($params['startTime']) : null;
        $endTime = isset($params['endTime']) ? strtotime($params['endTime']) : null;

        $orderLogic = A('Common/Order', 'Logic');
        try {
            $orderInfo = $orderLogic->searchByKeywords($hotelId,  $keywords, $pageIndex,  $pageSize, $type, $statusType, $startTime, $endTime);
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }
    
        // 格式化数据
        foreach ($orderInfo['subOrder'] as &$subOrder) {
            $names = array_column($subOrder['user'], 'name');            
            $subOrder['startdate'] = strtotime($subOrder['startdate']);
            $subOrder['enddate'] = strtotime($subOrder['enddate']);
            $subOrder['createtime'] = strtotime($subOrder['createtime']);
            $subOrder['checkoutdate'] = strtotime($subOrder['checkoutdate']);
            $subOrder['name'] = isset($names[0])?$names[0]:'';
            $subOrder['mobile'] = array_diff(array_column($subOrder['user'], 'mobile'), array(''));
            $subOrder['mobile'] = implode(',', $subOrder['mobile']);
            $subOrder['identity'] = array_diff(array_column($subOrder['user'], 'identity'), array(''));
            $subOrder['identity'] = implode(',',  $subOrder['identity']);
            $subOrder['statusText'] = $orderLogic->statusMap[LANG_SET][$subOrder['status']];
            unset($subOrder['user']);
        }
        unset($subOrder);
    
        return returnJson(200, 200, $orderInfo);
    }
    
    /**
     * 获取单个订单信息
     * @add Paddy 2016-11-21
     */
    public function getOrder() {
        $params = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'hotel' => 'notnull,notempty,id',
            'token' => 'notnull,notempty'
        );
        $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);
        $userId = $params['userId'];
        $token = $params['token'];
        $hotelId = $params['hotel'];
    
        $this->checkMobileToken($userId, $token);
    
        $orderInfoId = explode(',', $params['order']);
        $orderLogic = A('Common/Order', 'Logic');
        try {
            $orderInfo = $orderLogic->getOrderInfo($hotelId, $orderInfoId);
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }
    
        // 查找是否有子订单退款中
        $orderRoomIds = array_column($orderInfo[0]['rooms'], 'id');
        $orderRefundModel = D('OrderRefund');
        $orderRefundInfo = $orderRefundModel->getInfoByOrder($orderRoomIds);
        $orderInfo[0]['refunding'] = (empty($orderRefundInfo) || !in_array(ORDER_REFUND_APPLY, array_column($orderRefundInfo, 'status'))) ? DISABLE : ENABLE;
    
        // 处理数据
        unset($orderInfo[0]['hotelentity_id']);
        $orderInfo[0]['channelid'] = $orderInfo[0]['hotelchannel_id'];
        unset($orderInfo[0]['hotelchannel_id']);
        unset($orderInfo[0]['userlogin_id']);
        //$orderInfo[0]['pay'] = $orderInfo[0]['payment'];
        $orderInfo[0]['pay'] = number_format($orderInfo[0]['payment'] + $orderInfo[0]['otherUncollectePrice'], '2', '.', '');
        unset($orderInfo[0]['payment']);

        $orderPayRecordModel = D('OrderPayRecord');
        $payRecord = $orderPayRecordModel->getInfosByOrderinfoId($orderInfo[0]['id']);
        if(!empty($payRecord)){
            $payIds = array_column($payRecord, 'hotelpay_id');
            $payIds[] = 0;
            $hotelPayModel = D('HotelPay');
            $payInfo = $hotelPayModel->getInfo($payIds);
            $payInfo = getArrayValueAsIndex($payInfo, 'id');
            foreach ($payRecord as &$pay){
                switch (LANG_SET) {
                    case 'zh_cn':
                        $pay['name']=explode('/', $payInfo[$pay['hotelpay_id']]['name'])[0];
                        break;
                    case 'en_us':
                        $pay['name']=explode('/', $payInfo[$pay['hotelpay_id']]['name'])[1];
                        break;
                    case 'zh_tw':
                        $pay['name']=explode('/', $payInfo[$pay['hotelpay_id']]['name'])[2];
                        break;
                    default:
                        $pay['name']=explode('/', $payInfo[$pay['hotelpay_id']]['name'])[0];
                        break;
                }
            }
            unset($pay);
            $orderInfo[0]['pay_method'] = $payRecord;
        }else {
            $orderInfo[0]['pay_method'] = array();
        }
    
        // 获取是否还可重复发送短信房卡
        $orderInfoId = $orderInfo[0]['id'];
        if (empty($this->redisUtil)) {
            $this->redisUtil = new \Org\Util\RedisHelper(null, null, 'meizhu');
        }
        $this->redisUtil->db(C('REDIS_HOME_DB'))->table('orderRoomSendMobile');
        $sendTimesItem = $this->redisUtil->hMGet($orderInfoId);
        // 这个参数只是查看次数是否被允许，前端仍需根据每个子订单是否为锁掌柜房间，是否为入住状态，且拥有手机号，结束时间未过期判断能否显示重新发送
        $orderInfo[0]['canSendAgain'] = 1;
        if (!empty($sendTimesItem)) {
            $sendTimes = $sendTimesItem['times'];
            if ($sendTimes >= 3) {
                $orderInfo[0]['canSendAgain'] = 0;
            }
        }

        // 子订单
        if (!empty($orderInfo[0]['rooms'])) {
            foreach ($orderInfo[0]['rooms'] as &$room) {
                unset($room['createtime']);
                unset($room['creator']);
                unset($room['name']);
                unset($room['mobile']);
                unset($room['identity']);
                unset($room['orderinfo_id']);
                $room['roomid'] = $room['roominfo_id'];
                unset($room['roominfo_id']);
                $room['pay'] = $room['payment'];
                unset($room['payment']);
                $room['startdate'] = strtotime($room['startdate']);
                $room['enddate'] = strtotime($room['enddate']);
                $room['checkoutdate'] = strtotime($room['checkoutdate']);
                $room['type'] = $room['roomtype_name'];
                $room['room'] = $room['roominfo_name'];
                unset($room['roomtype_name']);
                unset($room['roominfo_name']);
                foreach ($room['user'] as &$user) {
                    $user = array(
                        'userRoom' => $user['userroom_id'],
                        'orderUser' => $user['orderuser_id'],
                        'name' => $user['name'],
                        'mobile' => $user['mobile'],
                        'identity' => $user['identity'],
                        'idsex' => $user['idsex'],
                        'idnation' => $user['idnation'],
                        'idaddress' => $user['idaddress'],
                        'printCount' => $user['printcount'],
                        'isdelete' => $user['isdelete'],
                    );
                }
                unset($user);
            }
            unset($room);
        }else {
            returnJson(403, 202, null);
        }
    
        returnJson(200, 200, $orderInfo[0]);
    }

    /**
     * 移动端入住订单发短信接口 返回短信数据 不经过第三方接口
     * @modify AmosZhong 2016-08-08  创建
     */
    public function resendMobileCheckInOrderSMS() {
        $param = I('post.');

        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'hotel' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'order' => 'notnull,notempty,id',
            'orderUser' => 'notnull,notempty,id',
        );
        $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);

        $userId = $param['userId'];
        $token = $param['token'];
        $hotelId = $param['hotel'];

        //检验token
        $this->checkMobileToken($userId, $token);

        $orderRoomId = $param['order'];
        $orderUserId = $param['orderUser'];
        $orderLogic = A('Common/Order', 'Logic');

        try {
            $smsResult = $orderLogic->resendMobileCheckInOrderSMS($hotelId, $orderRoomId, $orderUserId);
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }

        $data = array(
            'roomName' => $smsResult['0'],
            'startTime' => $smsResult['1'],
            'endTime' => $smsResult['2'],
            'url' => $smsResult['3']
        );

        returnJson(200, 200, $data);
    }

     /**
     * @description  获取身份证数据
     * @modify wenhui 2016-06-19
     */
    public function getInfoByIdentity() {
        $param = I('post.');

        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'hotel' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'identity' => 'IDCard',
        );
        $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);

        $userId = $param['userId'];
        $token = $param['token'];
        $identity = isset($param['identity']) ? $param['identity'] : null;
        if (is_null($identity)) {
            returnJson(403, 510);
            return;
        }

        //检验token
        $this->checkMobileToken($userId, $token);

        $orderInfoModel = D('OrderInfo');
        $orderInfos = $orderInfoModel->getInfoByHotelAndDate($param['hotel']);
        $orderInfoIdAll = array_column($orderInfos, 'id');

        $orderUserModel = D('OrderUser');
        $orderUserInfo = $orderUserModel->getInfoByIdentity($identity, $orderInfoIdAll);
        if (empty($orderUserInfo['identity'])) {
            returnJson(403, 510);
            return;
        }

        // 组装数据
        unset($orderUserInfo['id']);
        unset($orderUserInfo['orderinfo_id']);
        unset($orderUserInfo['userlogin_id']);
        unset($orderUserInfo['areacode']);
        unset($orderUserInfo['mobile']);
        unset($orderUserInfo['isdelete']);

        returnJson(200, 200, $orderUserInfo);
    }

    /**
     * 获取转换汇率
     * @modify wenhui 2017-12-19 创建
     */
    public function getTransCurrencyRate() {
        $param = I('post.');

        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'hotel' => 'notnull,notempty,id',
            'transCurrencyId' => 'notnull,notempty,id',
        );

        $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);

        $userId = $param['userId'];
        $token = $param['token'];
        $hotelId = $param['hotel'];
        $transCurrencyId = $param['transCurrencyId'];

        //检验token
        $this->checkMobileToken($userId, $token);

        // 获取默认货币
        $currencyHotelModel = D('CurrencyHotel');
        $defaultCurrency = $currencyHotelModel->getDefaultCurrency($hotelId);
        $currencyId = isset($defaultCurrency['currency_id']) ? $defaultCurrency['currency_id'] : 8 ; // 人民币

        $currencyLogic = A('Common/Currency', 'Logic');
        $rateValue = 1;
        if ($currencyId != $transCurrencyId) {
            $rateValue = $currencyLogic->exchangeRates($transCurrencyId, $currencyId, []);
        }

        returnJson(200, 200, ['rateValue' => $rateValue]);
    }

}
